<template>
  <div class="dashboard-container">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="mb20">
      <el-col :span="6">
        <el-card class="stat-card stat-card-primary">
          <div class="stat-content">
            <div class="stat-number">{{ todayAlarms }}</div>
            <div class="stat-label">今日报警</div>
            <div class="stat-change" :class="{ 'increase': todayChange > 0, 'decrease': todayChange < 0 }">
              <i :class="todayChange > 0 ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
              {{ Math.abs(todayChange) }}%
            </div>
          </div>
          <div class="stat-icon">
            <i class="el-icon-warning"></i>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card stat-card-success">
          <div class="stat-content">
            <div class="stat-number">{{ pendingAlarms }}</div>
            <div class="stat-label">待处理</div>
            <div class="stat-desc">紧急：{{ emergencyAlarms }}件</div>
          </div>
          <div class="stat-icon">
            <i class="el-icon-time"></i>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card stat-card-warning">
          <div class="stat-content">
            <div class="stat-number">{{ processingAlarms }}</div>
            <div class="stat-label">处理中</div>
            <div class="stat-desc">平均用时：{{ avgProcessTime }}分钟</div>
          </div>
          <div class="stat-icon">
            <i class="el-icon-loading"></i>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card stat-card-info">
          <div class="stat-content">
            <div class="stat-number">{{ completedAlarms }}</div>
            <div class="stat-label">已完成</div>
            <div class="stat-desc">完成率：{{ completionRate }}%</div>
          </div>
          <div class="stat-icon">
            <i class="el-icon-circle-check"></i>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <!-- 左侧图表区域 -->
      <el-col :span="16">
        <!-- 实时报警趋势 -->
        <el-card class="chart-card mb20">
          <div slot="header" class="clearfix">
            <span class="chart-title">实时报警趋势</span>
            <el-button-group style="float: right;">
              <el-button size="mini" :type="timeRange === '24h' ? 'primary' : ''" @click="changeTimeRange('24h')">24小时</el-button>
              <el-button size="mini" :type="timeRange === '7d' ? 'primary' : ''" @click="changeTimeRange('7d')">7天</el-button>
              <el-button size="mini" :type="timeRange === '30d' ? 'primary' : ''" @click="changeTimeRange('30d')">30天</el-button>
            </el-button-group>
          </div>
          <div id="alarmTrendChart" style="width: 100%; height: 350px;"></div>
        </el-card>

        <!-- 报警类型分布 -->
        <el-card class="chart-card">
          <div slot="header" class="clearfix">
            <span class="chart-title">报警类型分布</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <div id="alarmTypePieChart" style="width: 100%; height: 300px;"></div>
            </el-col>
            <el-col :span="12">
              <div id="alarmLevelChart" style="width: 100%; height: 300px;"></div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

      <!-- 右侧信息区域 -->
      <el-col :span="8">
        <!-- 紧急报警列表 -->
        <el-card class="urgent-card mb20">
          <div slot="header" class="clearfix">
            <span class="chart-title">
              <i class="el-icon-warning" style="color: #F56C6C;"></i>
              紧急报警
            </span>
            <el-badge :value="urgentAlarmList.length" class="item" style="float: right;">
              <el-button size="mini" icon="el-icon-refresh" @click="getUrgentAlarms">刷新</el-button>
            </el-badge>
          </div>
          <div class="urgent-list">
            <div 
              v-for="alarm in urgentAlarmList" 
              :key="alarm.alarmId"
              class="urgent-item"
              @click="handleAlarmDetail(alarm.alarmId)"
            >
              <div class="urgent-header">
                <el-tag type="danger" size="mini">{{ getAlarmTypeName(alarm.alarmType) }}</el-tag>
                <span class="urgent-time">{{ formatTime(alarm.alarmTime) }}</span>
              </div>
              <div class="urgent-title">{{ alarm.alarmTitle }}</div>
              <div class="urgent-location">
                <i class="el-icon-location-outline"></i>
                {{ alarm.incidentLocation }}
              </div>
            </div>
            <div v-if="urgentAlarmList.length === 0" class="urgent-empty">
              <i class="el-icon-success" style="color: #67C23A;"></i>
              <p>暂无紧急报警</p>
            </div>
          </div>
        </el-card>

        <!-- 实时活动动态 -->
        <el-card class="activity-card">
          <div slot="header" class="clearfix">
            <span class="chart-title">
              <i class="el-icon-bell"></i>
              实时动态
            </span>
          </div>
          <el-timeline class="activity-timeline">
            <el-timeline-item
              v-for="activity in activityList"
              :key="activity.id"
              :timestamp="formatTime(activity.time)"
              size="large"
              :type="getActivityType(activity.type)"
            >
              <div class="activity-content">
                <h4>{{ activity.title }}</h4>
                <p>{{ activity.description }}</p>
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>

    <!-- 底部区域 -->
    <el-row :gutter="20" class="mt20">
      <!-- 学校报警热力图 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header" class="clearfix">
            <span class="chart-title">学校报警热力图</span>
          </div>
          <div id="schoolHeatmapChart" style="width: 100%; height: 350px;"></div>
        </el-card>
      </el-col>
      
      <!-- 处理效率统计 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header" class="clearfix">
            <span class="chart-title">处理效率统计</span>
          </div>
          <div id="efficiencyChart" style="width: 100%; height: 350px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 地图弹窗 -->
    <el-dialog title="报警详情" :visible.sync="mapDialogVisible" width="80%" append-to-body>
      <div id="alarmMapContainer" style="width: 100%; height: 500px;"></div>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { 
  getAlarmStatistics, 
  getTimeStatistics, 
  getTypeStatistics,
  getAlarmHotspots,
  listEmergencyAlarms,
  listRealtimeAlarms
} from "@/api/campus/alarm"

export default {
  name: "Dashboard",
  data() {
    return {
      // 统计数据
      todayAlarms: 0,
      todayChange: 0,
      pendingAlarms: 0,
      emergencyAlarms: 0,
      processingAlarms: 0,
      avgProcessTime: 0,
      completedAlarms: 0,
      completionRate: 0,
      
      // 图表实例
      alarmTrendChart: null,
      alarmTypePieChart: null,
      alarmLevelChart: null,
      schoolHeatmapChart: null,
      efficiencyChart: null,
      
      // 数据
      timeRange: '24h',
      urgentAlarmList: [],
      activityList: [],
      
      // 弹窗控制
      mapDialogVisible: false,
      
      // 定时器
      refreshTimer: null,
      wsConnection: null
    };
  },
  mounted() {
    this.initCharts();
    this.loadDashboardData();
    this.startAutoRefresh();
    this.initWebSocket();
  },
  beforeDestroy() {
    this.clearTimer();
    this.closeWebSocket();
    this.disposeCharts();
  },
  methods: {
    /** 初始化图表 */
    initCharts() {
      this.$nextTick(() => {
        this.alarmTrendChart = echarts.init(document.getElementById('alarmTrendChart'));
        this.alarmTypePieChart = echarts.init(document.getElementById('alarmTypePieChart'));
        this.alarmLevelChart = echarts.init(document.getElementById('alarmLevelChart'));
        this.schoolHeatmapChart = echarts.init(document.getElementById('schoolHeatmapChart'));
        this.efficiencyChart = echarts.init(document.getElementById('efficiencyChart'));
        
        // 监听窗口大小变化
        window.addEventListener('resize', this.handleResize);
      });
    },
    
    /** 加载仪表盘数据 */
    async loadDashboardData() {
      try {
        // 加载统计数据
        await Promise.all([
          this.loadStatistics(),
          this.loadTrendChart(),
          this.loadTypeDistribution(),
          this.loadHeatmap(),
          this.loadEfficiencyChart(),
          this.loadUrgentAlarms(),
          this.loadActivities()
        ]);
      } catch (error) {
        console.error('加载仪表盘数据失败:', error);
      }
    },
    
    /** 加载统计数据 */
    async loadStatistics() {
      const response = await getAlarmStatistics({
        timeRange: '24h'
      });
      const data = response.data;
      
      this.todayAlarms = data.todayAlarms || 0;
      this.todayChange = data.todayChange || 0;
      this.pendingAlarms = data.pendingAlarms || 0;
      this.emergencyAlarms = data.emergencyAlarms || 0;
      this.processingAlarms = data.processingAlarms || 0;
      this.avgProcessTime = data.avgProcessTime || 0;
      this.completedAlarms = data.completedAlarms || 0;
      this.completionRate = data.completionRate || 0;
    },
    
    /** 加载趋势图表 */
    async loadTrendChart() {
      const response = await getTimeStatistics({
        timeRange: this.timeRange
      });
      
      const option = {
        title: {
          text: '报警趋势',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['报警数量', '处理数量'],
          top: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: response.data.xAxisData
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '报警数量',
            type: 'line',
            data: response.data.alarmData,
            smooth: true,
            itemStyle: { color: '#F56C6C' }
          },
          {
            name: '处理数量',
            type: 'line',
            data: response.data.handleData,
            smooth: true,
            itemStyle: { color: '#67C23A' }
          }
        ]
      };
      
      this.alarmTrendChart.setOption(option);
    },
    
    /** 加载类型分布图表 */
    async loadTypeDistribution() {
      const typeResponse = await getTypeStatistics();
      
      // 报警类型饼图
      const typeOption = {
        title: {
          text: '报警类型',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [
          {
            name: '报警类型',
            type: 'pie',
            radius: '70%',
            data: typeResponse.data.typeData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      
      // 报警级别柱状图
      const levelOption = {
        title: {
          text: '报警级别',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: ['一般', '较重', '严重', '特别严重']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '数量',
            type: 'bar',
            data: typeResponse.data.levelData,
            itemStyle: {
              color: function(params) {
                const colors = ['#409EFF', '#E6A23C', '#F56C6C', '#DD1F1F'];
                return colors[params.dataIndex];
              }
            }
          }
        ]
      };
      
      this.alarmTypePieChart.setOption(typeOption);
      this.alarmLevelChart.setOption(levelOption);
    },
    
    /** 加载热力图 */
    async loadHeatmap() {
      const response = await getAlarmHotspots();
      
      const option = {
        title: {
          text: '学校报警分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        visualMap: {
          min: 0,
          max: 100,
          calculable: true,
          inRange: {
            color: ['#50a3ba', '#eac736', '#d94e5d']
          },
          textStyle: {
            color: '#000'
          }
        },
        geo: {
          map: 'china',
          roam: true,
          scaleLimit: {
            min: 1,
            max: 2
          },
          zoom: 1.2,
          top: 60,
          label: {
            normal: {
              show: false,
              fontSize: '10',
              color: 'rgba(0,0,0,0.7)'
            }
          },
          itemStyle: {
            normal: {
              borderColor: 'rgba(0, 0, 0, 0.2)'
            },
            emphasis: {
              areaColor: '#f2d5ad',
              shadowOffsetX: 0,
              shadowOffsetY: 0,
              borderWidth: 0
            }
          }
        },
        series: [
          {
            name: '报警数量',
            type: 'scatter',
            coordinateSystem: 'geo',
            data: response.data.heatmapData,
            symbolSize: function(val) {
              return Math.max(val[2] / 10, 8);
            },
            label: {
              formatter: '{b}',
              position: 'right',
              show: false
            },
            itemStyle: {
              color: '#F56C6C'
            },
            emphasis: {
              label: {
                show: true
              }
            }
          }
        ]
      };
      
      this.schoolHeatmapChart.setOption(option);
    },
    
    /** 加载效率图表 */
    async loadEfficiencyChart() {
      // 模拟效率数据
      const option = {
        title: {
          text: '处理效率',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['平均处理时间', '及时处理率'],
          top: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        },
        yAxis: [
          {
            type: 'value',
            name: '时间(分钟)',
            position: 'left'
          },
          {
            type: 'value',
            name: '比率(%)',
            position: 'right'
          }
        ],
        series: [
          {
            name: '平均处理时间',
            type: 'bar',
            yAxisIndex: 0,
            data: [45, 38, 42, 35, 40, 25, 30],
            itemStyle: { color: '#409EFF' }
          },
          {
            name: '及时处理率',
            type: 'line',
            yAxisIndex: 1,
            data: [88, 92, 89, 95, 91, 98, 96],
            itemStyle: { color: '#67C23A' }
          }
        ]
      };
      
      this.efficiencyChart.setOption(option);
    },
    
    /** 加载紧急报警 */
    async loadUrgentAlarms() {
      const response = await listEmergencyAlarms();
      this.urgentAlarmList = response.rows.slice(0, 5); // 只显示前5条
    },
    
    /** 加载活动动态 */
    loadActivities() {
      // 模拟活动数据
      this.activityList = [
        {
          id: 1,
          type: 'alarm',
          title: '新增报警',
          description: '学校A收到校园欺凌报警',
          time: new Date(Date.now() - 5 * 60 * 1000)
        },
        {
          id: 2,
          type: 'process',
          title: '开始处理',
          description: '张老师开始处理报警AL20241215001',
          time: new Date(Date.now() - 15 * 60 * 1000)
        },
        {
          id: 3,
          type: 'complete',
          title: '处理完成',
          description: '报警AL20241215002处理完成',
          time: new Date(Date.now() - 30 * 60 * 1000)
        }
      ];
    },
    
    /** 切换时间范围 */
    changeTimeRange(range) {
      this.timeRange = range;
      this.loadTrendChart();
    },
    
    /** 获取紧急报警 */
    async getUrgentAlarms() {
      await this.loadUrgentAlarms();
    },
    
    /** 查看报警详情 */
    handleAlarmDetail(alarmId) {
      this.$router.push(`/campus/alarm?alarmId=${alarmId}`);
    },
    
    /** 开始自动刷新 */
    startAutoRefresh() {
      this.refreshTimer = setInterval(() => {
        this.loadStatistics();
        this.loadUrgentAlarms();
        this.loadActivities();
      }, 30000); // 30秒刷新一次
    },
    
    /** 清除定时器 */
    clearTimer() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer);
        this.refreshTimer = null;
      }
    },
    
    /** 初始化WebSocket */
    initWebSocket() {
      const wsUrl = `${process.env.VUE_APP_WS_API}/websocket/campus-alarm/dashboard`;
      this.wsConnection = new WebSocket(wsUrl);
      
      this.wsConnection.onopen = () => {
        console.log('仪表盘WebSocket连接成功');
      };
      
      this.wsConnection.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          this.handleWebSocketMessage(data);
        } catch (error) {
          console.error('WebSocket消息解析失败:', error);
        }
      };
      
      this.wsConnection.onerror = (error) => {
        console.error('WebSocket连接错误:', error);
      };
      
      this.wsConnection.onclose = () => {
        console.log('WebSocket连接关闭');
        // 重连机制
        setTimeout(() => {
          this.initWebSocket();
        }, 5000);
      };
    },
    
    /** 处理WebSocket消息 */
    handleWebSocketMessage(data) {
      if (data.type === 'alarm_update') {
        // 实时更新统计数据
        this.loadStatistics();
        this.loadUrgentAlarms();
        
        // 添加到活动动态
        this.activityList.unshift({
          id: Date.now(),
          type: 'alarm',
          title: '新增报警',
          description: data.message,
          time: new Date()
        });
        
        // 只保留最新的10条动态
        if (this.activityList.length > 10) {
          this.activityList = this.activityList.slice(0, 10);
        }
      }
    },
    
    /** 关闭WebSocket */
    closeWebSocket() {
      if (this.wsConnection) {
        this.wsConnection.close();
        this.wsConnection = null;
      }
    },
    
    /** 销毁图表 */
    disposeCharts() {
      if (this.alarmTrendChart) this.alarmTrendChart.dispose();
      if (this.alarmTypePieChart) this.alarmTypePieChart.dispose();
      if (this.alarmLevelChart) this.alarmLevelChart.dispose();
      if (this.schoolHeatmapChart) this.schoolHeatmapChart.dispose();
      if (this.efficiencyChart) this.efficiencyChart.dispose();
      
      window.removeEventListener('resize', this.handleResize);
    },
    
    /** 处理窗口大小变化 */
    handleResize() {
      if (this.alarmTrendChart) this.alarmTrendChart.resize();
      if (this.alarmTypePieChart) this.alarmTypePieChart.resize();
      if (this.alarmLevelChart) this.alarmLevelChart.resize();
      if (this.schoolHeatmapChart) this.schoolHeatmapChart.resize();
      if (this.efficiencyChart) this.efficiencyChart.resize();
    },
    
    /** 格式化时间 */
    formatTime(time) {
      return this.parseTime(time, '{m}-{d} {h}:{i}');
    },
    
    /** 获取报警类型名称 */
    getAlarmTypeName(type) {
      const types = {
        1: '校园欺凌',
        2: '暴力事件',
        3: '威胁恐吓',
        4: '财物损失',
        5: '其他安全事件'
      };
      return types[type] || '未知';
    },
    
    /** 获取活动类型 */
    getActivityType(type) {
      const types = {
        alarm: 'danger',
        process: 'primary',
        complete: 'success'
      };
      return types[type] || 'info';
    }
  }
};
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 50px);
}

.mb20 {
  margin-bottom: 20px;
}

.mt20 {
  margin-top: 20px;
}

/* 统计卡片样式 */
.stat-card {
  border: none;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  transition: all 0.3s;
}

.stat-card:hover {
  box-shadow: 0 4px 20px 0 rgba(0,0,0,.15);
  transform: translateY(-2px);
}

.stat-card .el-card__body {
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.stat-content {
  position: relative;
  z-index: 2;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 8px;
}

.stat-desc {
  font-size: 12px;
  color: #C0C4CC;
  margin-top: 4px;
}

.stat-change {
  font-size: 12px;
  margin-top: 8px;
}

.stat-change.increase {
  color: #F56C6C;
}

.stat-change.decrease {
  color: #67C23A;
}

.stat-icon {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 48px;
  opacity: 0.2;
}

.stat-card-primary .stat-icon {
  color: #409EFF;
}

.stat-card-success .stat-icon {
  color: #67C23A;
}

.stat-card-warning .stat-icon {
  color: #E6A23C;
}

.stat-card-info .stat-icon {
  color: #909399;
}

/* 图表卡片样式 */
.chart-card {
  border: none;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

/* 紧急报警卡片样式 */
.urgent-card {
  border: none;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.urgent-list {
  max-height: 400px;
  overflow-y: auto;
}

.urgent-item {
  padding: 12px 0;
  border-bottom: 1px solid #EBEEF5;
  cursor: pointer;
  transition: background-color 0.3s;
}

.urgent-item:hover {
  background-color: #F5F7FA;
}

.urgent-item:last-child {
  border-bottom: none;
}

.urgent-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.urgent-time {
  font-size: 12px;
  color: #909399;
}

.urgent-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.urgent-location {
  font-size: 12px;
  color: #606266;
}

.urgent-empty {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.urgent-empty i {
  font-size: 32px;
  margin-bottom: 8px;
}

/* 活动时间线样式 */
.activity-card {
  border: none;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.activity-timeline {
  max-height: 400px;
  overflow-y: auto;
}

.activity-content h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.activity-content p {
  margin: 0;
  font-size: 12px;
  color: #606266;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard-container {
    padding: 10px;
  }
  
  .stat-number {
    font-size: 24px;
  }
  
  .stat-icon {
    font-size: 36px;
  }
}
</style> 